<template>
  <div class="wrap">
    <input type="file" @change="handleFileUpload" accept=".docx" />
    <!-- <mavon-editor v-model="markdownContent" /> -->
    <div ref="editorElement" class="editorElement"></div>
  </div>
</template>
<script>
import mammoth from 'mammoth';
import { Editor, EditorContent } from "@tiptap/vue-2";
import StarterKit from "@tiptap/starter-kit";
import { Node } from "@tiptap/core";
import { exportAsDocx } from "./js/exportToWord.js";
import { markdownData } from "./js/markdown.js";
import { Markdown } from "tiptap-markdown";

export default {
  components: {
    EditorContent,
  },
  data() {
    return {
      editor: null,
      markdownContent: "",
    };
  },
  mounted() {
    const markDown =   Markdown.configure({
    html: true, // 禁止HTML标签
    breaks: true, // 将换行符转换为<br>
  })
    const CustomDiv = Node.create({
      name: "customDiv",
      group: "block",
      content: "inline*",
      attributes: "12ca",
      parseHTML() {
        return [{ tag: "div" }, { tag: "span" }];
      },
      renderHTML({ HTMLAttributes }) {
        console.log("HTMLAttributes===", HTMLAttributes);
        return ["div", HTMLAttributes, 0];
      },
    });

    this.editor = new Editor({
      element: this.$refs.editorElement,
      extensions: [StarterKit,markDown,],
      content: `<div class='customDiv' >Start typing...</div><p>我是P</p><span>我是sPan</span>`,
      // onUpdate: () => {
      //   // 内容变化时触发
      //   this.$emit("update", this.editor.getHTML());
      // },
    });
  },
  methods: {
    handleFileUpload(event) {
      const file = event.target.files[0];
      const reader = new FileReader();

      reader.onload = async (e) => {
        try {
          // 执行 Word 转 Markdown
          const result = await mammoth.convertToMarkdown({
            arrayBuffer: e.target.result,
          });

          // 将结果绑定到编辑器
          this.markdownContent = result.value;
          console.log('result.value===',result.value,typeof(result.value));
          // this.editor.commands.setContent(`### <a id="_Toc1459104569"></a><a id="_Toc325"></a>差动保护动作象征及处理`);
          this.editor.commands.setContent(this.markdownContent);
        } catch (err) {
          console.error("转换失败:", err);
        }
      };

      reader.readAsArrayBuffer(file);
    },
  },
  beforeDestroy() {
    // 销毁编辑器
    if (this.editor) {
      this.editor.destroy();
    }
  },
};
</script>
<style lang="scss" scoped>
.mainContent {
  display: flex;
  .toc-sidebar {
    width: 20%;
    .toc-item {
      white-space: nowrap;
      text-align: left;
      text-overflow: ellipsis;
      overflow: hidden;
      cursor: pointer;
      margin: 4px 0;
    }
  }
  .editorElement {
    flex: 1;
  }
}
</style>